//
//  RegiesterViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/4/12.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "RegiesterViewController.h"
#import "UserXieyiViewController.h"

@interface RegiesterViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UIButton *yanzhengmaBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (nonatomic,assign)BOOL agreeFlag;
@property (nonatomic,copy)NSString *yzmString;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *YZMTF;
@property (weak, nonatomic) IBOutlet UITextField *PWTF;
@property (nonatomic,strong)NSTimer *yzmTimer;
@property (nonatomic,assign)int yzmTime;
@property (weak, nonatomic) IBOutlet UILabel *xieyiLabel;

@end

@implementation RegiesterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"用户注册";
    self.nextBtn.layer.cornerRadius = 10.0;
    self.yanzhengmaBtn.layer.borderWidth = 1.0;
    self.yanzhengmaBtn.layer.cornerRadius = 8.0;
    [self.yanzhengmaBtn.layer setBorderColor:[YMColor(249, 137, 196)CGColor]];
    self.nextBtn.userInteractionEnabled = NO;
    self.PWTF.secureTextEntry = YES;
    
    [self.yanzhengmaBtn addTarget:self action:@selector(clickYanzhengmaButton) forControlEvents:UIControlEventTouchUpInside];
    [self.nextBtn addTarget:self action:@selector(clickNextButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *xieyiButton = [[UIButton alloc]initWithFrame:self.xieyiLabel.frame];
    [self.view addSubview:xieyiButton];
    xieyiButton.backgroundColor = [UIColor redColor];
    
    self.phoneTF.delegate = self;
    self.YZMTF.delegate = self;
    self.PWTF.delegate = self;
    self.phoneTF.tag = 1;
      self.PWTF.tag = 2;
    self.YZMTF.tag = 3;
}


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField.tag == 1)
    {
        NSString *pwStr = self.phoneTF.text;
        self.phoneTF.text = @"";
        self.phoneTF.text = pwStr;
    }
    if(textField.tag == 2)
    {
        NSString *pwStr = self.PWTF.text;
        self.PWTF.text = @"";
        self.PWTF.secureTextEntry = NO;
        self.PWTF.text = pwStr;
        self.PWTF.secureTextEntry = YES;
    }
    if(textField.tag == 3)
    {
        NSString *pwStr = self.YZMTF.text;
        self.YZMTF.text = @"";
        self.YZMTF.text = pwStr;
    }
    
}


-(void)shengchengYanZhengMa
{
    self.yzmString = [[NSString alloc]init];
    
    for(int i = 0;i < 6; i ++)
    {
        int m = arc4random() % 10;
        self.yzmString = [self.yzmString stringByAppendingString:[NSString stringWithFormat:@"%d",m]];
    }
    
    YMLog(@"随机生成的6位数位:%@",self.yzmString);
}

//点击验证码按钮
-(void)clickYanzhengmaButton
{
    
    NSUInteger phoneLength = self.phoneTF.text.length;
    if(phoneLength == 11)
    {
        self.yzmTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(yamTimeDisplay) userInfo:nil repeats:YES];
        self.yzmTime = 60;
        self.yanzhengmaBtn.userInteractionEnabled = NO;
        [self shengchengYanZhengMa];
        NSString *urlString = @"http://web.cr6868.com/asmx/smsservice.aspx";
        NSURL *url = [[NSURL alloc]initWithString:urlString];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
        
        request.HTTPMethod = @"POST";
         NSString *str = [NSString stringWithFormat:@"name=13602624302&pwd=5E06798C36C5FA7CE3ACEA8DE233&content=验证码为%@，请在一分钟内输入正确的验证码&mobile=%@&stime=&sign=是源医学&type=pt&extno=",self.yzmString,self.phoneTF.text];
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        
        NSOperationQueue *queue = [NSOperationQueue mainQueue];
        
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
        {
            
            if (data)
            {
                // 请求成功
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                YMLog(@"dict = %@",dict);
                [MBProgressHUD showSuccess:@"验证码发送成功!"];
            }
            else
            {
                self.yanzhengmaBtn.userInteractionEnabled = YES;
            }
        }];
    }
    else
    {
        [MBProgressHUD showError:@"请输入正确的手机号"];
    }

    
}
//验证码倒计时
-(void)yamTimeDisplay
{
    self.yzmTime --;
    if(self.yzmTime > 0)
    {
        self.yanzhengmaBtn.backgroundColor = [UIColor whiteColor];
        [self.yanzhengmaBtn setTitle:[NSString stringWithFormat:@"%ds",self.yzmTime] forState:UIControlStateNormal];
        [self.yanzhengmaBtn setTintColor:[UIColor whiteColor]];
        self.yanzhengmaBtn.userInteractionEnabled = NO;
    }
    else
    {
        [self.yanzhengmaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.yanzhengmaBtn setTitleColor:YMColor(249, 137, 196) forState:UIControlStateNormal];
        self.yanzhengmaBtn.layer.cornerRadius = 5.0;
        [self.yanzhengmaBtn setBackgroundColor:[UIColor clearColor]];
        self.yanzhengmaBtn.userInteractionEnabled = YES;
        [self.yzmTimer invalidate];
        self.yzmTimer = nil;
        self.yzmString = nil;
    }
    
}

//同意协议按钮
- (IBAction)clickAgreeBtn:(id)sender
{
    if(self.agreeFlag)
    {
        [self.agreeBtn setImage:[UIImage imageNamed:@"dl_Unselected"] forState:UIControlStateNormal];
        self.agreeFlag = NO;
        self.nextBtn.backgroundColor = YMColor(221, 221, 221);
        [self.nextBtn setTitleColor:YMColor(173, 173, 173) forState:UIControlStateNormal];
        self.nextBtn.userInteractionEnabled = NO;
    }
    else
    {
        [self.agreeBtn setImage:[UIImage imageNamed:@"dl_Selected"] forState:UIControlStateNormal];
        self.agreeFlag = YES;
        self.nextBtn.backgroundColor = YMColor(249, 137, 196);
        [self.nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.nextBtn.userInteractionEnabled = YES;
    }

}

//点击下一步按钮
-(void)clickNextButton
{
    if([self.YZMTF.text isEqualToString:self.yzmString])
    {
        if(![self.PWTF.text isEqualToString:@""])
        {
            if(self.PWTF.text.length >= 6)
            {
                NSString *urlString = @"http://120.24.178.16:8080/Health/baby/register.do";
                NSURL *url = [[NSURL alloc]initWithString:urlString];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
                
                request.HTTPMethod = @"POST";
                NSString *str = [NSString stringWithFormat:@"account=%@&mail=0&mobile=0&sex=0&devNo=0&weight=0&tall=0&password=%@&question=0&answer=0",self.phoneTF.text,self.PWTF.text];
                NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
                [request setHTTPBody:data];
                
                NSOperationQueue *queue = [NSOperationQueue mainQueue];
                
                [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
                 {
                     if (data)
                     {
                         // 请求成功
                         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                         YMLog(@"dict = %@",dict);
                        if([[dict objectForKey:@"code"] isEqualToString:@"0"])
                        {
                            [self.yzmTimer invalidate];
                            self.yzmTimer = nil;
                            
                            self.yanzhengmaBtn.backgroundColor = [UIColor clearColor];
                            [self.yanzhengmaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                            self.yanzhengmaBtn.userInteractionEnabled = YES;
                            [MBProgressHUD showSuccess:@"注册成功"];
                            [[NSUserDefaults standardUserDefaults]setObject:self.phoneTF.text forKey:@"userAccount"];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [self.navigationController popToRootViewControllerAnimated:YES];
                            });
                        }
                         if([[dict objectForKey:@"code"] isEqualToString:@"2"])
                         {
                             [MBProgressHUD showError:@"账号已存在"];
                         }
                     }
                 }];
            }
            else
            {
                [MBProgressHUD showError:@"密码长度不能小于6位"];
            }
        }
        else
        {
            [MBProgressHUD showError:@"密码不能为空"];
        }
    }
    else
    {
        [MBProgressHUD showError:@"验证码错误"];
    }
}

//网络请求过程中，出现任何错误（断网，连接超时等）会进入此方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.yanzhengmaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.yzmTimer invalidate];
    self.yzmTimer = nil;
    self.yzmTime = 60;
    self.yanzhengmaBtn.userInteractionEnabled = YES;
    [MBProgressHUD showError:@"网络不给力"];
}

//点击空白处收缩键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.phoneTF resignFirstResponder];
    [self.YZMTF resignFirstResponder];
    [self.PWTF resignFirstResponder];
}
- (IBAction)clickUserXieyi:(id)sender {
    UserXieyiViewController *user = [[UserXieyiViewController alloc]init];
    [self.navigationController pushViewController:user animated:YES];
}


@end
